<?php

namespace cms\modules\v1\models;

use common\models\Functions;
use common\models\Status;
use Yii;
use yii\base\Exception;

/**
 * Class UserActiveRecord
 * @package cms\modules\v1\models
 */
class CommonInfo extends Common
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%common_info}}';
    }

    public function getList() {
        try {

            $list = static::getByWhere([
                'status' => Status::COMMON_RADIO_YES,
            ], ['*'], '');

            $result = [];
            foreach ($list as $k => $v) {
                $groupName = $v['group'];
                $result[$groupName][] = [
                    'id' => (int) $v['id'],
                    'name' => $v['name'],
                    'value' => $v['type'] == 1 ? intval($v['value']) : ($v['value']),
                    'comment' => $v['comment'],
                    'type' => $v['type'],
                ];
            }
            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    public function saveInfo() {
        try {
            $post = Yii::$app->request->post();
            $id = (int) $post['id'];

            if (empty($post['id'])) {
                throw new Exception('ID不能为空');
            }
            $data['value'] = $post['value'];

            if (! empty($id)) {
                $res = static::updateData($data, ['id' => $id]);
                if ($res === false) {
                    throw new Exception(ApiException::SYSTEM_ERROR_CONTACT_SERVER);
                }
            }

            return Functions::formatRestAPI(0, '修改成功');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getInfo($id = 0) {
        try {
            $info = static::getOneInfoById($id);

            if (empty($info)) {
                throw new Exception('未知会员卡信息');
            }
            return Functions::formatRestAPI(0, '', $info);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }
}
